using DG.Tweening;
using Sirenix.OdinInspector;
using UnityEngine;

namespace DoTweenExtends
{
    public abstract class BaseTween : MonoBehaviour
    {
        [SerializeField] private string id;

        [Title("Base")] 
        [SerializeField] private AutoPlayMode autoPlay = AutoPlayMode.OnStart;

        public bool autoKill = true;
        // public bool killOnDestroy = true;
        public float delay = 0f;
        public int loops = 1;

        [ShowIf("ShouldLoopType", false)] public LoopType loopType = LoopType.Restart;

        public Tween Tween { private set; get; }

        private void OnEnable()
        {
            if (autoPlay == AutoPlayMode.OnEnable)
                Play();
        }

        private void Start()
        {
            if (autoPlay == AutoPlayMode.OnStart)
                Play();
        }

        private void OnDestroy()
        {
            Kill();
        }

        public void Play()
        {
            if (Tween == null)
            {
                Tween = GetTween();
                Tween.Play();
            }
            else
            {
                Tween.Restart();
            }
        }

        public void Kill()
        {
            Tween?.Kill();
        }

        private Tween GetTween()
        {
            Tween = CreateTween();
            Tween.SetAutoKill(autoKill);

            Tween.SetLoops(loops, loopType);
            Tween.SetDelay(delay);

            if (!string.IsNullOrEmpty(id))
                Tween.SetId(id);
            return Tween;
        }


        protected abstract Tween CreateTween();

        #region 编辑器辅助

        private bool ShouldLoopType()
        {
            return !(loops == 1 || loops == 0);
        }

        #endregion
    }
}